package fun.tan90.easy.binlog.manager.dict;

import cn.hutool.core.io.resource.ResourceUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;

import java.util.*;
import java.util.stream.Collectors;

/**
 * description TODO
 * company 铁人科技
 *
 * @author 陈浩杰
 * @date 2023/11/20 13:56
 */
public class Dict {

    private static final Map<String, Map<String, String>> DICT = new HashMap<>();
    private static final Map<String, List<DictItem>> DICT_LIST = new HashMap<>();

    public static final String RULE_STATUS = "ruleStatus";

    public static final String OUTPUT_TYPE = "outputType";

    static {
        String dictJson = ResourceUtil.readUtf8Str("dict.json");
        JSONObject dict = JSONUtil.parseObj(dictJson);
        for (String key : dict.keySet()) {
            List<DictItem> dictItemList = dict.getJSONArray(key).toList(DictItem.class);
            Map<String, String> dictMap = new HashMap<>();
            for (DictItem item : dictItemList) {
                dictMap.put(item.getKey(), item.getValue());
            }
            DICT.put(key, dictMap);

            dictItemList = dictItemList.stream().filter(DictItem::isShow).sorted(Comparator.comparingInt(DictItem::getSort)).collect(Collectors.toList());
            DICT_LIST.put(key, dictItemList);
        }
    }

    public static String dict(String dictType, String key) {
        return Optional.ofNullable(DICT.get(dictType)).map(n -> n.getOrDefault(key, "未知")).orElse("未知");
    }

    public static List<DictItem> dict(String dictType) {
        return Optional.ofNullable(DICT_LIST.get(dictType)).orElseGet(ArrayList::new);
    }
}
